package com.wx.auth.servlet;

import com.wx.auth.utils.AuthUtil;
import net.sf.json.JSONObject;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.*;

/**
 * @Author: lijunwei
 * @Time: 2018/6/24 0:08
 */
public class CallBackServlet extends HttpServlet {
    private String dbUrl;
    private String driverName;
    private String userName;
    private String passWord;
    private Connection conn = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;

    @Override
    public void init(ServletConfig config) throws ServletException {
        try {
            this.dbUrl = config.getInitParameter("dbUrl");
            this.driverName = config.getInitParameter("driverName");
            this.userName = config.getInitParameter("userName");
            this.passWord = config.getInitParameter("passWord");
            Class.forName(driverName);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
//        System.out.println("---------------"+);
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String code = req.getParameter("code");
        //-------code--------081RxxN01pUs3Z1PJFJ01xCIN01RxxNk
        System.out.println("-------code--------"+code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ AuthUtil.APPID
                + "&secret="+AuthUtil.APPSECRET
                + "&code="+code
                + "&grant_type=authorization_code";
        //-----url--002--------https://api.weixin.qq.com/sns/oauth2/access_token?
        // appid=wx73f59af1123b83bb&secret=b2ea07066153e7147582f1ac995297fb
        // &code=081RxxN01pUs3Z1PJFJ01xCIN01RxxNk&grant_type=authorization_code
        System.out.println("-----url--002--------"+url);
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        System.out.println("------jsonObject--------------"+jsonObject.toString());
        String openid = jsonObject.getString("openid");

        //-------openid--------oC2oN1M0cX7Pe3jyZ3AbHUy1aiTc
        System.out.println("-------openid--------"+openid);
        String token = jsonObject.getString("access_token");
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+token
                + "&openid="+openid
                + "&lang=zh_CN";
        //{"openid":"oC2oN1M0cX7Pe3jyZ3AbHUy1aiTc",
        // "nickname":"李俊伟",
        // "sex":1,
        // "language":"zh_CN",
        // "city":"海淀",
        // "province":"北京",
        // "country":"中国",
        // "headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqXuHtq2wpHZEichRPvCGiaohiahIQeJJkLmRe6B4JNqxiaZPc8Rb99rIFyjL5rASd4YFgRqXOGP4Pjfg/132",
        // "privilege":[]}
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
        System.out.println(userInfo);
         String nickname = userInfo.getString("nickname");
        //只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段。
      //  String unionid = userInfo.getString("unionid");//----因为测试号没有与开放平台绑定,因此无法获取该字段----------------------

        //1、使用微信用户信息直接登录，无需注册和绑定
        //req.setAttribute("info", userInfo);
        //req.getRequestDispatcher("/index1.jsp").forward(req, resp);

        //2、将微信与当前系统的账号进行绑定,即数据库中有用户表,用户表中有登录名和密码,当用户用微信登录的时候需要
        try {
            String nickName = getNickName(openid);
            if(!"".equals(nickName)){
                //绑定成功
                req.setAttribute("nickName", nickName);
                req.getRequestDispatcher("/index2.jsp").forward(req, resp);
            }else{
                //未绑定
                req.setAttribute("openid", openid);
                req.setAttribute("nickName", nickname);
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public String getNickName(String unionid) throws SQLException{
        String nickName = "";
        conn = DriverManager.getConnection(dbUrl, userName, passWord);
        String sql = "select NIKENAME from user where OPENID=?";
        ps = conn.prepareStatement(sql);
        ps.setString(1, unionid);
        rs = ps.executeQuery();
        while(rs.next()){
            nickName = rs.getString("NICKNAME");
        }
        rs.close();
        ps.close();
        conn.close();
        return nickName;
    }

    public int updUser(String openid,String account,String password) throws SQLException{
        conn = DriverManager.getConnection(dbUrl, userName, passWord);
        String sql = "update user set OPENID=? where ACCOUNT=? and PASSWORD=?";
        ps = conn.prepareStatement(sql);
        ps.setString(1, openid);
        ps.setString(2, account);
        ps.setString(3, password);
        int temp = ps.executeUpdate();

        rs.close();
        ps.close();
        conn.close();
        return temp;
    }
    public int insertUser(String ACCOUNT,String PASSWORD,String NIKENAME ,String OPENID) throws SQLException, UnsupportedEncodingException {
        System.out.println("-----------添加数据--------------"+NIKENAME);
       // NIKENAME= URLDecoder.decode(NIKENAME,"UTF-8");
       // System.out.println("-----------添加数据002--------------"+NIKENAME);
        conn = DriverManager.getConnection(dbUrl, userName, passWord);
        String sql = "INSERT INTO user (`ID`, `ACCOUNT`, `PASSWORD`, `NIKENAME`, `OPENID`) VALUES (NULL, ?, ?, ?, ?);";
        ps = conn.prepareStatement(sql);
        ps.setString(1, ACCOUNT);
        ps.setString(2, PASSWORD);
        ps.setString(3, NIKENAME);
        ps.setString(4, OPENID);
        //nickName
        int temp = ps.executeUpdate();
        rs.close();
        ps.close();
        conn.close();
        return temp;
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        System.out.println("------------doPost------");
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        String openid = req.getParameter("openid");
        String nickName = req.getParameter("nickName");
        System.out.println("-------doPost参数----------"+nickName);
        try {
           // int temp = updUser(openid, account, password);
            int temp = insertUser(account, password, nickName, openid);
            if(temp>0){
                System.out.println("-------------------账号绑定成功---------------");
            }else{
                System.out.println("-----------------账号绑定失败-----------------------");
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

